import React, {Component} from 'react';

import {
    AsyncStorage
} from 'react-native';

const FLAG_FAVORITE_PREFIX = 'favorite_'

export default class FavoriteDao {
    constructor(flag) {
        this.flag = FLAG_FAVORITE_PREFIX + flag
    }

    /**
     * 保存key
     * @param key
     */
    saveFavorite(key) {
        this.updataFavorite(key, true)
    }

    /**
     * 更新对应flag的keys
     * @param key
     * @param isAdd
     */
    updataFavorite(key, isAdd) {
        AsyncStorage.getItem(this.flag, (error, result) => {
            if (!error) {
                let favoriteKeys = []
                if (result) {
                    favoriteKeys = JSON.parse(result)
                }
                let index = favoriteKeys.indexOf(key)
                if (isAdd) {
                    if (index === -1) favoriteKeys.push(key)
                } else {
                    if (index !== -1) favoriteKeys.splice(index, 1)
                }
                AsyncStorage.setItem(this.flag, JSON.stringify(favoriteKeys))
            }
        })
    }

    /**
     * 删除key
     * @param key
     */
    removeFavorite(key) {
        this.updataFavorite(key, false)
    }

    /**
     * 获取favoriteKeys集合
     * @returns {Promise}
     */
    getFavoriteKeys() {
        return new Promise((resolve, reject) => {
            AsyncStorage.getItem(this.flag, (error, result) => {
                console.warn(JSON.parse(result))
                if (error) {
                    reject(error)
                } else {
                    try {
                        resolve(JSON.parse(result))
                    } catch (e) {
                        reject(e)
                    }
                }
            })
        })
    }
}
